<template>
    <div class="app">
        <div>
            <div class="button_saveandfile">
                <div class="filea">
                    <span class="fontb">请上传电台Excel文件:</span>
                    <el-form label-width="80px" class="demo-ruleForm">
                        <el-form-item>
                            <el-upload action="" :http-request="upload" :before-upload="beforeUploadFile" ref="upload">
                                <el-button type="success" plain class="shangchuan">上传文件<i
                                        class="el-icon-upload2"></i></el-button>
                            </el-upload>
                        </el-form-item>
                    </el-form>
                    <el-button type="primary" @click="dialogFormVisible = true; this.radioAndProgramAddVO.programId = null;" class="primary" plain>新增电台与节目</el-button>
                    <el-button type="primary" @click="radioAndProgramInfoExport"  class="primary">导出电台与节目数据</el-button>
                </div>
               
                <div class="radio_search_area" @keyup.enter="keyDown($event)">
                    <el-input v-model="searchRadioName" class="radio_search_input" placeholder="请输入查询电台名"
                        style="margin-left: 2%;" />
                    <el-button type="warning" plain @click="searchRadioAndProgram" class="radio_search_submit"
                        style="margin-left: 4%;margin-top: -0.3%;">查询</el-button>
                    <el-button type="danger" @click="deleteAllRadioAndProgram" class="delete_button">一键删除电台数据</el-button>
                </div>
            </div>
            <el-divider></el-divider>
            <el-dialog v-model="dialogFormVisible" title="新增(更新)电台">
                <el-form>
                    <el-form-item label="电台名称" :label-width="formLabelWidth">
                        <el-input autocomplete="off" v-model="radioAndProgramAddVO.radioName" placeholder="电台名称"/>
                    </el-form-item>
                </el-form>
                <el-form>
                    <el-form-item label="节目名称" :label-width="formLabelWidth">
                        <el-input autocomplete="off" v-model="radioAndProgramAddVO.programName" placeholder="节目名称" />
                    </el-form-item>
                </el-form>
                <div class="demo-time-range">
                    <span class="jianju">开始时间</span>
                    <el-time-select v-model="radioAndProgramAddVO.startTime" :max-time="endTime" class="mr-4" placeholder="开始时间" style="margin-top: -3px;"
                        start="06:00" step="00:30" end="22:00" />
                    <span class="jianju">结束时间</span>
                    <el-time-select v-model="radioAndProgramAddVO.endTime" :min-time="startTime" placeholder="结束时间" start="06:00" style="margin-top: -3px;"
                        step="00:30" end="22:00" />
                </div>
                <el-form>
                    <el-form-item label="所属电台：" :label-width="formLabelWidth">
                        <el-input autocomplete="off" v-model="radioAndProgramAddVO.belongRadioName" placeholder="所属电台"  style="width:200px"/>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="cancellation">取消</el-button>
                        <el-button type="primary" @click="saveRadioAndProgram">
                            保存
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
        <!-- -------------------------------------------------------tab-------------------------------------------------- -->
        <div class="tabdiv">
            <el-table :data="radioAndProgramVOList" style="width:100%;height:615px">
                <el-table-column type="index" width="50" fixed="left">
                </el-table-column>
                <el-table-column label="电台名称" width="250" fixed="left">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.radioVO.radioName }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="节目名称" width="180" show-overflow-tooltip fixed="left">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.programName }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="开始时间" width="180">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.startTime }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="结束时间" width="180">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.endTime }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" width="180" class="xishu">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.createTime }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" width="180" class="xishu">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.lastUpdateTime }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="所属电台" width="180" class="xishu">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.radioVO.belongRadioName }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="修改信息">
                    <template #default="scope">
                        <el-button type="primary" size="small"
                            @click="handleEdit(scope.$index, scope.row.id)">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页器 -->
        <div class="block-box">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
                :page-sizes="[1, 5, 10, 20]" :page-size="pageSize" :total="total"
                layout="total, sizes, prev, pager, next, jumper">
            </el-pagination>
        </div>
    
    </div>
</template>

<script>

import axios from '../api/index'
import { mapState } from 'vuex'
import { ElLoading } from 'element-plus';
export default {
    // computed:{
    //    ...mapState(['userInfo'])
    // },
    data() {
        return {
            searchRadioName: '',
            dialogTableVisible: false,
            dialogFormVisible: false,
            currentPage: 1, // 当前页码
            pageSize: 20, // 每页的数据条数
            total: 0, // 总条数
            radioAndProgramVOList: [],
            radioAndProgramAddVO: {
                programId:null, //节目id
                radioId:null,//电台id
                radioName: '',//电台名称
                programName: '', //节目名称
                startTime: '', //开始时间
                endTime:'',//结束时间 
                belongRadioName:'' //所属电台
            },        

        }
    },
    methods: {
        // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
        beforeUploadFile(file) {
            console.log('before upload')
            console.log(file)
            let extension = file.name.substring(file.name.lastIndexOf('.') + 1)
            let size = file.size / 1024 / 1024
            if (extension !== 'xlsx') {
                this.$message.warning('只能上传后缀是.xlsx的文件')
            }
            if (size > 100) {
                this.$message.warning('文件大小不得超过100M')
            }
        },
        // 上传
        upload(param) {
            //const formData = new FormData()
            //formData.append('file', param.file)   
            this.$refs.upload.clearFiles(); //去掉文件列表 
            let loadingInstance = ElLoading.service({
                fullscreen: true,
                lock: true,
                text: "电台数据正在上传中，请耐心等待",
                background: "rgba(0, 0, 0, 0.7)"
            });
            axios.postRequest('/radio/import', param.file)
            .then(res => {
                if (res.data.code === 200) {
                    this.$message({
                        type: 'success',
                        message: '电台数据导入完成，请使用'
                    })
                    this.searchRadioAndProgram()
                } else {
                    this.$message({
                        type: 'error',
                        message: '文件上传失败'+res.data.message
                    })
                }
                setTimeout(() => {
                    loadingInstance.close();//我们的获取接口数据函数
                }, 2000);
            })
        },
        //编辑查询方法------
        handleEdit(index, row) {
            this.dialogFormVisible = true
            // 调ajax后台详情接口(id)
            let base = `/radio/searchRadioAndProgramByProgramId/${row}`
            axios.getRequest(base)
                .then((res) => {
                    if (res.data.code === 200) {
                        this.radioAndProgramAddVO.radioId = res.data.data.radioVO.id
                        this.radioAndProgramAddVO.radioName = res.data.data.radioVO.radioName
                        this.radioAndProgramAddVO.programName = res.data.data.programName
                        this.radioAndProgramAddVO.startTime = res.data.data.startTime
                        this.radioAndProgramAddVO.endTime = res.data.data.endTime
                        this.radioAndProgramAddVO.programId = row
                        this.radioAndProgramAddVO.belongRadioName = res.data.data.radioVO.belongRadioName
                        //this.searchRadioAndProgram()
                    } else {
                        this.$message({
                            type: 'error',
                            message: '编辑电台数据失败！'+res.data.message
                        })
                    }
                })

        },
        //监听 pagesize 改变的事件
        handleSizeChange(newSize) {
            console.log(newSize + '+++++++++++++++++');
            this.pageSize = newSize;//重新指定每页数据量
            this.searchRadioAndProgram();//带着新的分页请求获取数据
        },
        //监听 页码值 改变的事件
        handleCurrentChange(newPage) {
            console.log(newPage + '-----------------');
            this.currentPage = newPage;//重新指定当前页
            this.searchRadioAndProgram();//带着新的分页请求获取数据
        },
        saveRadioAndProgram() {
            axios.postRequest('/radio/saveRadioAndProgram', this.radioAndProgramAddVO)
            .then(res => {
                if (res.data.code === 200) {
                    this.searchRadioAndProgram()
                    this.$message({
                        type: 'success',
                        message: '操作成功！'
                    })
                } else {
                    this.$message({
                        type: 'error',
                        message: '操作失败！'+res.data.message
                    })
                }
            })
            this.dialogFormVisible = false
            this.radioAndProgramAddVO.radioName = ''
            this.radioAndProgramAddVO.programName = ''
            this.radioAndProgramAddVO.startTime = ''
            this.radioAndProgramAddVO.endTime = ''
            this.radioAndProgramAddVO.radioId = ''
            this.radioAndProgramAddVO.programId = ''
            this.radioAndProgramAddVO.belongRadioName = ''
        },
        keyDown(e){
            if (e.key == 'Enter') {
                console.log('回车事件被执行')
                this.searchRadioAndProgram();
            }
        },
        searchRadioAndProgram() {
            var pageInfo = {pageNum: this.currentPage, pageSize: this.pageSize,radioName: this.searchRadioName }
            axios.postRequest('/radio/searchRadioAndProgramPage',pageInfo)
                .then(res => {
                    if (res.data.code === 200) {
                        this.radioAndProgramVOList = res.data.data.radioAndProgramVOList
                        //注意：分页这里必须要将total转换成数字！！！
                        this.total = parseInt(res.data.data.total)  
                    } else {
                        this.$message({
                            type: 'error',
                            message: '数据出错！'+res.data.message
                        })
                    }
                })
        },
        cancellation() {
            this.dialogFormVisible = false
            this.radioAndProgramAddVO.radioName = ''
            this.radioAndProgramAddVO.programName = ''
            this.radioAndProgramAddVO.startTime = ''
            this.radioAndProgramAddVO.endTime = ''
            this.radioAndProgramAddVO.radioId = ''
            this.radioAndProgramAddVO.programId = ''
            this.radioAndProgramAddVO.belongRadioName = ''
        },
        //下载文件
        downloadFile(res, fileName) {
            let blob = new Blob([res.data]); //res为从后台返回的数据
            //let blob = new Blob([res]); 
            if (!fileName) {
                fileName = res.headers['content-disposition'].split('filename=').pop();
            }
            if ('msSaveOrOpenBlob' in navigator) {
                window.navigator.msSaveOrOpenBlob(blob, fileName);
            } else {
                const elink = document.createElement('a');
                elink.download = fileName;
                elink.style.display = 'none';
                elink.href = URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href);
                document.body.removeChild(elink);
            }
        },
        radioAndProgramInfoExport() {
            axios.getRequest('/radio/getRadioExport?radioName='+ this.searchRadioName, null, 'blob')
                .then(res => {
                    this.$message({
                        type: 'warning',
                        message: '正在导出电台与节目数据，请耐心等待'
                })
                this.downloadFile(res, '电台与节目数据表.xlsx')
            })
        },
        deleteAllRadioAndProgram() {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {        
                axios.getRequest(`/radio/deleteAllRadioAndProgram`)
                .then( 
                    res => {
                        if (res.data.code === 200) {
                            this.searchRadioAndProgram();
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        } 
                        else{
                            this.$message({
                                type: 'error',
                                message: '删除失败!'+res.data.message
                            });
                        }
                    }
                )
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
      }
    },
    mounted() {
        this.searchRadioAndProgram();
        window.addEventListener("keydown", this.keyDown);
    },
    destroyed() {        
         // 销毁事件
      window.addEventListener("keydown", this.keyDown);
    }
}
</script>
    
<style scope>
.radio_search_area {
    margin-top: -60px;
    margin-left: 200px;
    font-size: 14px;
    display: flex;
    padding-left: 25%;
    width: 930px;
    height: 50px;
    line-height: 28px;
}

.radio_search_area .el-input {
    width: 170px;
    height: 30px;
}

.radio_search_area .radio_search_submit {
    margin-left: 10px;
}

.file {
    display: flex;
}

.filea {
    display: flex;
}
.filed{
    display: flex;
    margin-left: 320px;
    margin-top: -73px;
}

.fontb {
    width: 160px;
    font-size: 13px;
    margin-top: 20px;
    margin-left: 5px;
    height: 20px;
}

.demo-ruleForm {
    width: 0px;
    margin-left: -90px;
    margin-top: 6px;
}

.shangchuan {
    padding-top: 6px;
    margin-top: 8px;
}
.delete_button{
    margin-top: -0.3%;
}
.demo-time-range {
    margin-bottom: 10px;
}

.el-select {
    margin-top: 10px;
    width: 280px;
    margin-left: 12px;
    margin-right: 12px;
}



.jianju {
    height: 50px;
    align-items: center;
    text-align: center;
}

.primary {
    margin-top: 15px;
    margin-left:180px;
}

.cell {
    width: 250px;
    text-align: left;
}

body,
hr,
dl,
dt,
dd,
ul,
ol,
li,
h1,
h2,
h3,
h4,
h5,
h6,
pre,
form,
fieldset,
input,
textarea,
blockquote,
p {
    padding: 0;
    margin: 0;
}

.el-dialog__headerbtn {
    display: none;
}

.block-box {
    width: 100%;
    height: 50px;
    margin-top: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>